<template>
  <div class="carbon-offset-page">
    <!-- 左侧导航栏 -->
    <div class="sidebar">
      <a-menu v-model:openKeys="openKeys" mode="inline">
        <a-sub-menu key="sub1" title="碳汇项目管理">
          <a-menu-item key="1" @click="changePage('projectList')">查看所有项目</a-menu-item>
        </a-sub-menu>
        <a-sub-menu key="sub2" title="碳汇交易管理">
          <a-menu-item key="3" @click="changePage('tradeList')">查看交易列表</a-menu-item>
        </a-sub-menu>
      </a-menu>
    </div>

    <!-- 右侧内容区域 -->
    <div class="content">
      <!-- 项目列表 -->
      <div v-if="currentPage === 'projectList'" class="content-card">
        <a-card title="碳汇项目列表">
          <a-button type="primary" @click="showProjectModal" style="margin-bottom: 20px">新增项目</a-button>
          <a-table
            :columns="projectColumns"
            :dataSource="projects"
            rowKey="name"
            bordered
            @change="handleChange"
            class="carbon-assets-table"
            :pagination="pagination"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'action'">
                <span class="action-buttons">
                  <a type="link" @click="viewProjectDetail(record)">详细信息</a>
                  <a-divider type="vertical" />
                  <a type="link" danger @click="deleteProject(record)">删除</a>
                </span>
              </template>
            </template>
          </a-table>
        </a-card>
      </div>

      <!-- 碳汇交易列表 -->
      <div v-if="currentPage === 'tradeList'" class="content-card">
        <h2>碳汇交易列表</h2>
        <a-table :columns="tradeColumns" :dataSource="trades" rowKey="date" bordered>
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'action'">
              <a-button type="link">详细信息</a-button>
            </template>
          </template>
        </a-table>
        <a-button type="primary" @click="showTradeModal" style="margin-top: 16px">新增交易</a-button>
      </div>

      <!-- 新增或编辑项目的弹窗 -->
      <a-modal v-model:visible="isProjectModalVisible" title="新增碳汇项目" @ok="addProject">
        <a-form :model="newProject" layout="vertical">
          <a-form-item label="项目名称">
            <a-input v-model:value="newProject.projectName" />
          </a-form-item>
          <a-form-item label="项目类型">
            <a-select
              v-model:value="newProject.assetCategoryId"
              style="width: 100%"
              :fieldNames="{ label: 'caCategoryName', value: 'caCategoryId' }"
              placeholder="选择碳资产类型"
              :options="assetsCategories"
            ></a-select>
          </a-form-item>
          <a-form-item label="碳汇量">
            <a-input v-model:value="newProject.carbonSequestrationAmount" />
          </a-form-item>
          <a-form-item label="认证状态">
            <a-select v-model:value="newProject.certificationStatus">
              <a-select-option value="已认证">已认证</a-select-option>
              <a-select-option value="待认证">待认证</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="详细描述">
            <a-textarea v-model="newProject.description" rows="4" />
          </a-form-item>
        </a-form>
      </a-modal>

      <!-- 新增交易弹窗 -->
      <a-modal v-model:visible="isTradeModalVisible" title="新增碳汇交易" @ok="addTrade">
        <a-form :model="newTrade" layout="vertical">
          <a-form-item label="交易日期">
            <a-date-picker v-model="newTrade.date" />
          </a-form-item>
          <a-form-item label="类型">
            <a-input v-model="newTrade.type" />
          </a-form-item>
          <a-form-item label="交易量">
            <a-input v-model="newTrade.amount" />
          </a-form-item>
          <a-form-item label="交易类型">
            <a-select v-model="newTrade.tradeType">
              <a-select-option value="买入">买入</a-select-option>
              <a-select-option value="卖出">卖出</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="详细描述">
            <a-textarea v-model="newTrade.description" rows="4" />
          </a-form-item>
        </a-form>
      </a-modal>
    </div>
  </div>
</template>

<script setup>
  import { message } from 'ant-design-vue';
  import { h, reactive, computed, ref, onMounted } from 'vue';
  import { carbonSequestration } from '/@/api/Carbon module/Carbon asset module/Carbon asset project/carbonSequestration';
  import { smartSentry } from '/@/lib/smart-sentry';

  const openKeys = ref(['sub1']);
  const currentPage = ref('projectList');
  const isProjectModalVisible = ref(false);
  const isTradeModalVisible = ref(false);

  const projects = ref([]);

  const trades = ref([
    { date: '2023-01-01', type: '碳汇', amount: '100 吨', tradeType: '买入' },
    { date: '2023-02-01', type: '碳汇', amount: '50 吨', tradeType: '卖出' },
  ]);

  const projectColumns = [
    { title: '项目名称', dataIndex: 'projectName', key: 'projectName' },
    { title: '类型', dataIndex: 'caCategoryName', key: 'caCategoryName' },
    { title: '碳汇量', dataIndex: 'carbonSequestrationAmount', key: 'carbonSequestrationAmount' },
    { title: '认证状态', dataIndex: 'certificationStatus', key: 'certificationStatus' },
    { title: '操作', key: 'action', scopedSlots: { customRender: 'action' } },
  ];

  const tradeColumns = [
    { title: '交易日期', dataIndex: 'date', key: 'date' },
    { title: '类型', dataIndex: 'type', key: 'type' },
    { title: '交易量', dataIndex: 'amount', key: 'amount' },
    { title: '交易类型', dataIndex: 'tradeType', key: 'tradeType' },
    { title: '操作', key: 'action', scopedSlots: { customRender: 'action' } },
  ];

  const newProject = ref({
    projectName: '',
    assetCategoryId: '',
    carbonSequestrationAmount: '',
    certificationStatus: '待认证',
    description: '',
  });

  const newTrade = ref({
    date: '',
    type: '',
    amount: '',
    tradeType: '买入',
    description: '',
  });

  const showProjectModal = () => {
    newProject.value = {
      projectName: '',
      assetCategoryId: '',
      carbonSequestrationAmount: '',
      certificationStatus: '',
      description: '',
    };
    isProjectModalVisible.value = true;
  };

  const showTradeModal = () => {
    isTradeModalVisible.value = true;
  };

  const addProject = async () => {
    console.log(newProject.value);
    if (newProject.value.projectName && newProject.value.assetCategoryId && newProject.value.carbonSequestrationAmount) {
      // 添加新项目
      try {
        await carbonSequestration.Add({ ...newProject.value });
        queryData();
      } catch (error) {
        console.log(error);
      }
    } else {
      // 在此处处理表单验证失败的情况
      console.log('请填写所有必需的字段。');
    }
    isProjectModalVisible.value = false;
  };

  const addTrade = () => {
    projects.value.push({ ...newProject.value });
    isTradeModalVisible.value = false;
  };

  const deleteProject = async (record) => {
    try {
      await carbonSequestration.Delete(record.sequestrationProjectId);
      queryData();
    } catch (error) {
      console.log(error);
    }
  };

  const changePage = (page) => {
    currentPage.value = page;
  };

  // 查询碳汇列表
  const pagination = computed(() => ({
    total: total.value,
    pageSize: queryFormState.pageSize,
    current: queryFormState.pageNum,
    showTotal: (total) => `总共${total}项`,
  }));
  const queryFormState = reactive({
    pageNum: 1,
    pageSize: 10,
  });
  const tableLoading = ref(false);
  const total = ref(0); //总数
  const queryForm = reactive({ ...queryFormState });
  async function queryData() {
    tableLoading.value = true;
    try {
      queryForm.pageNum = queryFormState.pageNum; // 确保页码同步
      queryForm.pageSize = queryFormState.pageSize;
      let queryResult = await carbonSequestration.query(queryForm);
      projects.value = queryResult.data.list;
      total.value = queryResult.data.total;
    } catch (e) {
      smartSentry.captureError(e);
    } finally {
      tableLoading.value = false;
    }
  }
  const handleChange = (pagination, filters, sorter) => {
    queryFormState.pageNum = pagination.current; // 更新当前页
    queryFormState.pageSize = pagination.pageSize; // 更新页大小
    queryData();
  };

  // 碳资产类型
  const assetsCategories = ref([]);
  async function queryAssetsCategory() {
    let queryResult = await carbonSequestration.queryAssetsCategory({
      pageNum: 1,
      pageSize: 100,
    });
    assetsCategories.value = queryResult.data.list;
  }

  onMounted(() => {
    queryData();
    queryAssetsCategory();
  });
</script>

<style scoped>
  .carbon-offset-page {
    display: table;
    width: 100%;
  }

  .sidebar {
    display: table-cell;
    width: 220px;
    vertical-align: top;
    background: #fff;
  }

  .content {
    display: table-cell;
    padding-left: 10px;
    background-color: #f0f2f5;
  }

  .content-card {
    padding: 24px;
    background: white;
    border-radius: 8px;
    /* box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); */
  }
</style>
